package com.leyou.order.controller;

import com.leyou.order.dto.OrderDTO;
import com.leyou.order.entity.Order;
import com.leyou.order.service.IorderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class OrderController {

    @Autowired
    private IorderService orderService;

    @PostMapping
    public ResponseEntity<Long> createOrder(@Valid @RequestBody OrderDTO orderDTO) {
        return ResponseEntity.status(HttpStatus.CREATED).body(orderService.createOrder(orderDTO));
    }

    /**
     * 查询订单状态
     *
     * @param orderId
     * @return
     */
    @GetMapping("{orderId}")
    public ResponseEntity<Order> queryOrder(@PathVariable("orderId") Long orderId) {
        return ResponseEntity.ok(orderService.queryOrder(orderId));
    }

    /**
     * 请求下单并生成支付连接
     *
     * @param orderId
     * @return
     */
    @GetMapping("url/{orderId}")
    public ResponseEntity<String> getPayUrl(@PathVariable("orderId") Long orderId) {
        return ResponseEntity.ok(orderService.getPayUrl(orderId));
    }

    @PostMapping(value = "/pay/wx/notify", produces = "application/xml")
    public Map<String, String> hello(@RequestBody Map<String, String> result) {
        log.info("[支付回调] 接收微信支付回调, 结果:{}", result);
        orderService.handleNotify(result);
        // 返回成功
        Map<String, String> msg = new HashMap<>();
        msg.put("return_code", "SUCCESS");
        msg.put("return_msg", "OK");
        return msg;
    }

    @GetMapping("state/{orderId}")
    public ResponseEntity<Integer> queryPayState(@PathVariable("orderId") Long orderId) {
        return ResponseEntity.ok(orderService.queryPayState(orderId));
    }



}
